/*
 * Rhy Tooltip
 * 
 * @author Tristan Maindron
 * @dependencies rhy.core.wrapper, rhy.core.selector, rhy.core.config, rhy.core.view
 * 
 */

Rhy.extra.tooltip = {
    
    apply: function(o, content){
        $r.on(o, 'mouseover', function(e){
            var source = $r.evt.source(e);
            
            var div = document.createElement('div');
            div.className = "rhy-tooltip-container";
            
            if(typeof(source.id) != 'undefined'){
                div.id = source.id + '-rhy-tooltip';
            }
            
            if(typeof(content) == "string"){
                div.innerHTML = content;
            }
            else{
                div.appendChild(content);
            }
            
            source.rhyTooltip = div;
            document.body.appendChild(div);

            div.style.position = 'absolute';

            var left =  e.clientX - $r.vw.gp.getOffsetWidth(div)/2;
            var top = (e.clientY + 16);
            
            if(top < 0){
                top = e.clientY;
            }
            
            if(left < 0){
                left = e.clientX;
            }
            
            var ws = $r.vw.gp.getWindowsSize();
            
            if(ws.w < left + $r.vw.gp.getOffsetWidth(div)){
                left = e.clientX - $r.vw.gp.getOffsetWidth(div);
            }
            
            if(ws.h < top + $r.vw.gp.getOffsetHeight(div)){
                top = (e.clientY - $r.vw.gp.getOffsetHeight(div) - 16);
            }
            
            div.style.left = left + 'px';
            div.style.top = top + 'px';
            
            $r.on(div, 'mouseout', function(){
                document.body.removeChild(div);
            });
            
        });
        
        $r.on(o, 'mouseout', $r.ex.tooltip.mouseout);
    },
    
    mouseover: function(e){
        
    },
    
    mouseout: function(e){
        var source = $r.evt.source(e);
        var target = e.relatedTarget || e.toElement;

        if(typeof(source.rhyTooltip) != 'undefined' && target != source.rhyTooltip){
            document.body.removeChild(source.rhyTooltip);
            source.rhyTooltip = undefined;
        }
    }
    
}
